package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.payment.config.AlipayConfig;
import com.spzx.payment.service.AlipayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "支付管理")
@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;

    @Operation(summary = "支付宝支付")
    @GetMapping("/submitAlipay/{orderNo}")
    public AjaxResult submitAlipay(@PathVariable String orderNo){
        //调用AlipayService中支付宝支付的方法
        String from=alipayService.submitAlipay(orderNo);
        return AjaxResult.success(from);
    }
    @Operation(summary = "支付宝回调通知的接口")
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String,String> paramMap){

        try {
            //验证签名
            boolean flag = AlipaySignature.rsaCertCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);

            //判断是否验成功
            if (flag){
                String tradeStatus = paramMap.get("trade_status");
                //判断状态是否成功或完成
                if ("TRADE_SUCCESS".equals(tradeStatus)||"TRADE_FINISHED".equals(tradeStatus)){
                    //调用Alipayservice中更新支付状态的方法
                    alipayService.updatePaymentInfoStatus(paramMap);
                }

            }

        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        System.out.println("支付宝回调成功");
        System.out.println("paramMap = " + paramMap);
        return "failure";
    }

}
